##### Automator Shellscript (stdin mode) #####

USER_PROFILE="$HOME/.WineStarter"
PROFILE="/tmp/WineStarter"

# Export profile
cat > "${PROFILE}"

if [ -n "$(cat "${PROFILE}")" ] ; then

	# Import profile
	. "${PROFILE}"

	# Use history
	[ "${INPUT}" ] && sed -i "" -e "s|^HISTORY=\".*\"$|HISTORY=\"${INPUT}\"|" "${USER_PROFILE}"

	# Export environment valiables
	[ "${WINEPREFIX}" ] && export WINEPREFIX
	[ "${WINEDEBUG}" -a ! "${XTERM}" ] && export WINEDEBUG

	# For Homebrew Users
	[ -x "/usr/local/bin/wine" ] && PATH="/usr/local/bin:${PATH}"

	# For MacPorts Users
	[ -x "/opt/local/bin/wine" ] && PATH="/opt/local/bin:${PATH}"

	export PATH

	# Start up application priority	
	INPUT="${INPUT:-${HISTORY:-${APP_0:-${APP_1:-${APP_2}}}}}"

	# Virtual desktop
	if [ "${USE_VD}" ] ; then

		# Auto VD name
		[ "${USE_VD}" = "version" ] && USE_VD="$(echo $(wine --version))"

		VD="explorer /desktop=${USE_VD},${VD_SIZE_0:-${VD_SIZE_1:-${VD_SIZE_2}}}"

	fi

	# MSI executable support
	[ "$(echo "${INPUT}" | egrep -i "\.msi$" )" ] && MSIEXEC="msiexec /i"

	# Export start up script
	cat <<EOF > "${PROFILE}" && chmod +x "${PROFILE}"
wine ${VD} ${MSIEXEC} "${INPUT}"
EOF

	if [ -x "${XTERM}" ] ; then
	
		# Use xterm
		${XTERM} -geometry +0+0 -e bash -c "cat ${PROFILE}; ${PROFILE}" &

	else
	
		# Use background shell
		${PROFILE} &
	fi

fi
